﻿using HandyControl.Controls;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Win32;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using WpfApp_SmartParking_Base;
using WpfApp_SmartParking_Entities;
using WpfApp_SmartParking_IService;
using WpfApp_SmartParking_Models;
using WpfApp_SmartParking_Service;

namespace WpfApp_SmartParking.ViewModels;

public class MainViewModel : BindableBase
{
    private List<SysMenu>? sysMenus = null;

    private readonly IMenuService _menuService;
    private readonly IRegionManager _regionManager;

    private ObservableCollection<MenuItemModel> _menus = new ObservableCollection<MenuItemModel>();

    public ObservableCollection<MenuItemModel> Menus
    {
        get { return _menus; }
        set { SetProperty<ObservableCollection<MenuItemModel>>(ref _menus, value); }
    }

    public DelegateCommand<object?> OpenViewCommand { get; set; }

    public DelegateCommand? ChangeAccountCommand { get; set; }

    public DelegateCommand<object?>? UserAvatarsSelectItemChangeCommand { get; set; }

    public UserModel? CurrentLoginUser { get; set; }

    public List<string> Avatars { get; set; } = new List<string>() 
    {
        "pack://siteoforigin:,,,/Avatars/a01.jpg",
        "pack://siteoforigin:,,,/Avatars/a02.jpg",
        "pack://siteoforigin:,,,/Avatars/a03.png",
        "pack://siteoforigin:,,,/Avatars/a04.jpg",
        "pack://siteoforigin:,,,/Avatars/a05.png",
        "pack://siteoforigin:,,,/Avatars/a06.jpg",
        "pack://siteoforigin:,,,/Avatars/a07.jpg",
        "SelectFile"
    };


    public MainViewModel(
        IDialogService dialogService,
        IMenuService menuService,
        IRegionManager regionManager,
        IEventAggregator eventAggregator)
    {
        _menuService = menuService;
        _regionManager = regionManager;


        dialogService.ShowDialog("LoginView", result =>
        {
            if (result.Result != ButtonResult.OK)
            {
                Environment.Exit(0);
            }
            SysUser sysUser = result.Parameters.GetValue<SysUser>("user");
            InitLoginUserInfo(sysUser);

            sysMenus = menuService.GetMenuList().ToList();
            if (sysMenus != null && sysMenus.Count > 0)
            {
                Menus = LoadMenus(0);
            }
        });


        OpenViewCommand = new DelegateCommand<object?>(DoOpenChildView);

        ChangeAccountCommand = new DelegateCommand(DoRestart);

        UserAvatarsSelectItemChangeCommand = new DelegateCommand<object?>(DoReSetAvatar);

        //这样必须keepalive设置成true，通过匿名函数会被GC回收导致订阅失败，或者通过下面方法将抽成一个函数再类中
        eventAggregator.GetEvent<RefreshMenuEvent>().Subscribe(() =>
        {
            sysMenus = _menuService.GetMenuList().ToList();
            Menus = LoadMenus(0);
        },true);

        //eventAggregator.GetEvent<RefreshMenuEvent>().Subscribe(RefreshMenus);
    }

    private void InitLoginUserInfo(SysUser sysUser)
    {
        CurrentLoginUser = new UserModel() 
        {
            Id = sysUser.Id,
            Name = sysUser.Name,
            Avatar = $"pack://siteoforigin:,,,/Avatars/{sysUser.Avatar}",
            Password = sysUser.Password,
            Address = sysUser.Address,
            Phone = sysUser.Phone,
            Mobile = sysUser.Mobile,
            Gender = sysUser.Gender,
            Qq = sysUser.Qq,
            Status = sysUser.Status
        };
    }

    private void RefreshMenus()
    {
        sysMenus = _menuService.GetMenuList().ToList();
        Menus = LoadMenus(0);
    }

    /// <summary>
    /// 加载菜单
    /// </summary>
    private ObservableCollection<MenuItemModel> LoadMenus(int _parentId)
    {
        ObservableCollection<MenuItemModel> menuItemModels = new ObservableCollection<MenuItemModel>();
        var _items = sysMenus!.Where(it => it.ParentId == _parentId).OrderBy(it => it.Index).ToList();
        foreach (var item in _items)
        {
            MenuItemModel menuItemModel = new MenuItemModel()
            {
                MenuHeader = item.MenuHeader ?? "",
                MenuIcon = item.MenuIcon ?? "",
                TargetView = item.TargetView ?? ""
            };
            menuItemModel.Children = LoadMenus(item.MenuId);
            menuItemModels.Add(menuItemModel);
        }
        return menuItemModels;
    }

    /// <summary>
    /// 打开子页面
    /// </summary>
    /// <param name="menuItemModel"></param>
    private void DoOpenChildView(object? obj)
    {
        if (obj == null || !(obj is MenuItemModel))
            return;
        MenuItemModel menuItemModel = (MenuItemModel)obj;
        if (menuItemModel.Children.Count > 0) 
        {
            menuItemModel.IsExpanded = !menuItemModel.IsExpanded;
            return;
        }
        if (!string.IsNullOrEmpty(menuItemModel.TargetView))
            _regionManager.RequestNavigate("MainTabRegion", menuItemModel.TargetView);
    }

    private async void DoRestart()
    {
        string? executablePath = Process.GetCurrentProcess()?.MainModule?.FileName;
        if (string.IsNullOrEmpty(executablePath)) 
        {
            System.Windows.MessageBox.Show("未找到可执行文件！");
            return;
        }
        Process.Start(executablePath,"restart");
        await Task.Delay(500);
        Environment.Exit(0);
        //Application.Current.Shutdown();
    }


    private void DoReSetAvatar(object? selectItem)
    {
        if (selectItem != null && selectItem.ToString() == Avatars[Avatars.Count - 1]) 
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "*.jpg,*.png,*.jpeg|*.jpg;*.png;*.jpeg";
            if (dialog.ShowDialog() == true) 
            {
                
            }
            return;
        }
    }
}
